package team.pikachu.pikachuclient.teacher;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.telephony.PhoneNumberUtils;
import android.telephony.SmsManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import team.pikachu.pikachuclient.R;
import team.pikachu.pikachuclient.beans.Location;
import team.pikachu.pikachuclient.message.LocationAdapter;
import team.pikachu.pikachuclient.message.MsgUploadActivity;
import team.pikachu.pikachuclient.utils.HttpUtils;
import team.pikachu.pikachuclient.utils.IPConstants;
import team.pikachu.pikachuclient.utils.JsonUtils;
import team.pikachu.pikachuclient.utils.LogUtil;

public class PersonFragment extends Fragment {

    private String LOGTAG = LogUtil.makeLogTag(PersonFragment.class);

    private String DELIVERED_SMS_ACTION = "DELIVERED_SMS_ACTION";
    private String SENT_SMS_ACTION = "SENT_SMS_ACTION";
    private Intent sentIntent = new Intent(SENT_SMS_ACTION);
    private Intent deliverIntent = new Intent(DELIVERED_SMS_ACTION);
    private PendingIntent sentPI ;
    private PendingIntent deliverPI ;

    @BindView(R.id.building)
    AutoCompleteTextView mLocationText;
    @BindView(R.id.room)
    EditText mRoomText;
    @BindView(R.id.phone)
    TextView mPhoneText;
    @BindView(R.id.frg_person)
    View container;
    @BindView(R.id.troubleSpinner)
    Spinner spinner;

    @OnClick(R.id.phone)
    void onCall() {
        if (TextUtils.isEmpty(mLocationText.getText().toString())) {
            mLocationText.setError("请输入您所在的教学楼");
            mLocationText.requestFocus();
            return;
        } else if (TextUtils.isEmpty(mRoomText.getText().toString())) {
            mRoomText.setError("请输入您所在的教室");
            mRoomText.requestFocus();
            return;
        }
        Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + mPhoneText.getText().toString()));
        startActivity(intent);
    }

    @OnClick(R.id.send_msg)
    void onSendMsg() {
        if (TextUtils.isEmpty(mLocationText.getText().toString())) {
            mLocationText.setError("请输入您所在的教学楼");
            mLocationText.requestFocus();
            return;
        } else if (TextUtils.isEmpty(mRoomText.getText().toString())) {
            mRoomText.setError("请输入您所在的教室");
            mRoomText.requestFocus();
            return;
        }
        phone = mPhoneText.getText().toString();
        if (phone.equals(getString(R.string.phone_prompt))){
            Toast.makeText(getActivity(),"该地区暂无维修人员",Toast.LENGTH_LONG).show();
            return;
        }
        String msg = "请前往 " + mLocationText.getText().toString() + " " + mRoomText.getText().toString()
                + " 处理 " + trouble;
        SmsManager manager = SmsManager.getDefault();
        ArrayList<String> list = manager.divideMessage(msg);  //因为一条短信有字数限制，因此要将长短信拆分
        for (String text : list) {
            manager.sendTextMessage(phone, null, text, sentPI, deliverPI);
        }
    }

    private SharedPreferences pre;

    private String[] troubles;
    private String trouble;

    private static String phone;

    public PersonFragment() {
        // Required empty public constructor
    }

    public static PersonFragment newInstance() {
        return new PersonFragment();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_person, container, false);
        ButterKnife.bind(this, view);

        if (phone != null) {
            mPhoneText.setText(phone);
        }

        LocationAsy locationAsy = new LocationAsy();
        String locationPath = IPConstants.GET_LOCATIONS + pre.getInt(getString(R.string.pre_schoolid), 0);
        locationAsy.execute(locationPath);
//        mLocationText.requestFocus();
        mLocationText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mPhoneText.setText(getString(R.string.phone_prompt));
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        mLocationText.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Location location = (Location) parent.getItemAtPosition(position);
                String name = location.getLocation();
                mLocationText.setText(name);
                mRoomText.requestFocus();
                phone = location.getPhone();
                mPhoneText.setText(phone);
            }
        });

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                trouble = troubles[position];
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        sentPI = PendingIntent.getBroadcast(getActivity(), 0, sentIntent, 0);
        deliverPI = PendingIntent.getBroadcast(getActivity(), 0, deliverIntent, 0);

        checkSmsSend();
        checkSmsReceive();

        return view;
    }

    private void checkSmsSend() {
        getActivity().registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context _context, Intent _intent) {
                switch (getResultCode()) {
                    case Activity.RESULT_OK:
                        Toast.makeText(getActivity(),
                                "短信发送成功", Toast.LENGTH_SHORT)
                                .show();
                        break;
                    case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                        Toast.makeText(getActivity(),
                                "短信发送失败", Toast.LENGTH_SHORT)
                                .show();
                        break;
                    case SmsManager.RESULT_ERROR_RADIO_OFF:
                        break;
                    case SmsManager.RESULT_ERROR_NULL_PDU:
                        break;
                }
            }
        }, new IntentFilter(SENT_SMS_ACTION));
    }

    private void checkSmsReceive(){
        getActivity().registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context _context, Intent _intent) {
                Toast.makeText(getActivity(),
                        "收信人已经成功接收", Toast.LENGTH_SHORT)
                        .show();
            }
        }, new IntentFilter(DELIVERED_SMS_ACTION));
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        pre = context.getSharedPreferences("userInfo", Context.MODE_PRIVATE);
        troubles = getResources().getStringArray(R.array.trouble_type);
    }

    /**
     * 地址名自动补全
     * 适配器适配地址名字List
     */
    private class LocationAsy extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            return HttpUtils.sendPostMethod(params[0]);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
//            Log.d(LOGTAG,s);
            if (!isAdded())
                return;
            if (!s.equals(getString(R.string.timeout)) && !s.equals(getString(R.string.request_failed))) {

                Location[] locations = JsonUtils.readValue(s, Location[].class);

                assert locations != null;
                for (Location location : locations) {
                    Log.i(LOGTAG, location.toString());
                }

                List<Location> locationList = Arrays.asList(locations);
                LocationAdapter arrayAdapter = new LocationAdapter(getActivity(), android.R.layout.simple_list_item_1, locationList);
                arrayAdapter.setOnCompleteListener(new LocationAdapter.CompleteListener() {
                    @Override
                    public void onComplete(Location location) {
                        phone = location.getPhone();
                        mPhoneText.setText(phone);
                    }
                });
                mLocationText.setAdapter(arrayAdapter);

            }
        }
    }

}
